<?php
include './config/config.php';

$sql = "SELECT * FROM `pre_person` WHERE `id` = '{$_GET['personId']}' ";
$data = query($sql);
// todo 查询部门表
$depSql = "SELECT * FROM `pre_department`";
$DepList = queryAll($depSql);
// todo 查询岗位表
$jobSql = "SELECT * FROM `pre_job` WHERE depid = '{$data['depid']}'";
$JobList = queryAll($jobSql);
// pre($JobList);
// exit;

if ($_POST) {

  $id = $_POST['id'];
  $sql = "SELECT * FROM `pre_person` WHERE `id` != '$id'";
  $ckList = queryAll($sql);

  // todo 检测手机号
  if ($_POST['action'] == 'cmobile') {
    $val = $_POST['val'];

    foreach ($ckList as $item) {
      if ($val == $item['mobile']) {
        error("手机号不可用，请重新填写");
      }
    }

    success("手机号可用");
  }

  // todo 检测邮箱
  if ($_POST['action'] == 'cemail') {
    $val = $_POST['val'];

    foreach ($ckList as $item) {
      if ($val == $item['mobile']) {
        error("邮箱不可用，请重新填写");
      }
    }

    success("邮箱可用");
  }

  // todo 岗位和部门链选
  if ($_POST['action'] == 'cdep') {
    $val = $_POST['val'];

    if ($_POST['val'] == 0) {
      error("请选择");
    }

    $jobSql = "SELECT * FROM `pre_job` WHERE depid = '$val'";
    $jobList = queryAll($jobSql);
    // pre($dataList);
    // exit;
    if (!empty($jobList)) {
      success("查询成功", $jobList);
    } else {
      error("查询失败");
    }
  }


  // ? 接收上传参数
  $formData = [
    "name" => $_POST['name'],
    "mobile" => $_POST['mobile'],
    "sex" => $_POST['sex'],
    "email" => $_POST['email'],
    "address" => $_POST['address'],
    "depid" => $_POST['depid'],
    "jobid" => $_POST['jobid'],
  ];

  //  todo 检测文件是否上传
  if ($_FILES['avatar'] && $_FILES['avatar']['size'] > 0) {
    @delfile($data['avatar']);
    $avatar = upload("avatar");
    if ($avatar['code'] == 0) {
      ShowMsg($avatar['msg']);
      exit;
    } else {
      // ? 数据追加avatar
      $formData['avatar'] = $avatar['url'];
    }
  }

  $where = "`id` = '{$_POST['id']}'";

  $res = updataById("person", $formData, $where);

  if ($res) {
    ShowMsg($res['msg'], "personList.php");
  } else {
    ShowMsg("修改失败");
  }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include_once('common/meta.php'); ?>
</head>

<body>
  <!--<![endif]-->

  <?php include_once('common/header.php'); ?>

  <?php include_once('common/menu.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">修改员工信息</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="personList.php">PersonList</a> <span class="divider">/</span></li>
      <li class="active">PersonUpdata</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='personList.php'"><i class="icon-list"></i> 员工列表</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">

              <form id="updata_form" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?php echo $data['id']; ?>">

                <div class="form-group">
                  <label for="name">姓名</label>
                  <input type='text' id='name' placeholder='name' name='name' value='<?php echo $data['name']; ?>'>
                </div>

                <div class="form-group" style="display: inline-block;">
                  <label for="">头像</label>
                  <input type="file" id="avatar" name="avatar" class="input-xxlarge" hidden>
                  <label for="avatar">
                    <img src="<?php echo './upload/' . $data['avatar']; ?>" alt='' style='display:block;width:120px;height:120px;' id="img">
                  </label>
                </div>


                <div class="form-group">
                  <label for="mobile">手机</label>
                  <input type='text' id='mobile' placeholder='mobile' name='mobile' value='<?php echo $data['mobile']; ?>'>
                  <span id="cmobile"></span>
                </div>

                <div class="form-group">
                  <label>性别</label>
                  <label for="sex1" style="display: inline;">男</label>
                  <?php
                  if ($data['sex'] == 1) {
                    echo "<input type='radio' id='sex1' name='sex' value='1' checked>";
                  } else {
                    echo "<input type='radio' id='sex1' name='sex' value='1'>";
                  }
                  ?>
                  <label for="sex2" style="display: inline;">女</label>
                  <?php
                  if ($data['sex'] == 2) {
                    echo "<input type='radio' id='sex2' name='sex' value='2' checked>";
                  } else {
                    echo "<input type='radio' id='sex2' name='sex' value='2'>";
                  }
                  ?>
                </div>

                <div class="form-group">
                  <label for="email">邮箱</label>
                  <?php
                  echo "<input type='email' id='email' placeholder='email' name='email' value='{$data['email']}'>";
                  ?>
                  <span id="cemail"></span>
                </div>

                <div class="form-group">
                  <label for="address">地址</label>
                  <?php
                  echo "<input type='text' id='address' placeholder='address' name='address' value='{$data['address']}'>";
                  ?>
                </div>

                <div class="form-group">
                  <label for="depid">所属部门</label>
                  <select name="depid" id="depid">
                    <?php foreach ($DepList as $item) { ?>
                      <option value="<?php echo $item['id'] ?>" <?php echo $item['id'] == $data['depid'] ? 'selected' : '' ?>>
                        <?php echo $item['name']; ?>
                      </option>
                    <?php } ?>
                  </select>
                </div>

                <div class="form-group">
                  <label for="jobid">岗位</label>
                  <select name="jobid" id="jobid">
                    <?php foreach ($JobList as $item) { ?>
                      <option value="<?php echo $item['id']; ?>" <?php echo $item['id'] == $data['jobid'] ? 'selected' : ''; ?>>
                        <?php echo $item['name']; ?>
                      </option>
                    <?php } ?>
                  </select>
                </div>

                <label></label>
                <input class="btn btn-primary" type="submit" value="更新" />
              </form>
            </div>
          </div>
        </div>

        <?php include_once('common/footer.php'); ?>

      </div>
    </div>
  </div>

  <script src="./assets/lib/jquery-1.8.1.min.js"></script>
  <script>
    // 图片预览函数
    function GetObjectURL(file) {
      // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
      var url = null;

      //判断是否为IE浏览器还是google还是其他浏览器
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file)
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file)
      }

      return url
    }

    $("#avatar").change(function() {
      let file = $(this)[0].files[0] ? $(this)[0].files[0] : {};
      // console.log(file[0].files[0]);

      // return false;
      let url = GetObjectURL(file);
      $("#img").attr('src', url);
    });

    let id = $("input[name='id']").val();

    // todo 检测手机号
    $('#mobile').change(function() {
      let val = $(this).val();

      var reg = /(^1[3|4|5|7|8][0-9]{9}$)/;

      // console.log(reg.test(val));
      if (!reg.test(val)) {
        $("#cmobile").html("请输入正确的手机格式").css({
          "color": "red"
        });
        return false;
      }

      $.ajax({
        type: "post",
        url: "personAdd.php",
        data: {
          id,
          val,
          action: 'cmobile'
        },
        dataType: "json",
        success: function(res) {
          if (res.code === 1) {
            $("#cmobile").html(res.msg).css({
              "color": "green"
            });
          } else if (res.code === 0) {
            $("#cmobile").html(res.msg).css({
              "color": "red"
            });
          }
        },
        error: function(err) {
          console.log(err);
        }
      });
    })

    // todo 检测邮箱
    $('#email').change(function() {
      let val = $(this).val();

      $.ajax({
        type: "post",
        url: "personAdd.php",
        data: {
          id,
          val,
          action: 'cemail'
        },
        dataType: "json",
        success: function(res) {
          if (res.code === 1) {
            $("#cemail").html(res.msg).css({
              "color": "green"
            });
          } else if (res.code === 0) {
            $("#cemail").html(res.msg).css({
              "color": "red"
            });
          }
        },
        error: function(err) {
          console.log(err);
        }
      });
    })

    // todo 岗位所属检测
    $('#depid').change(function() {
      let val = $(this).val();
      console.log(val);
      // return false;
      $.ajax({
        type: "post",
        url: "personUpdata.php",
        data: {
          val,
          action: 'cdep'
        },
        dataType: "json",
        success: function(res) {
          if (res.code === 1) {
            let option = '';

            // alert(res.msg);
            res.data.forEach(element => {
              option += `<option value="${element.id}">${element.name}</option>`;

            });
            // console.log(option);
            $("#jobid").html(option);
          } else if (res.code === 0) {
            console.log(res.msg);
          }
        },
        error: function(err) {
          console.log(err);
        }
      });
    })
  </script>
</body>

</html>
<?php include_once('common/script.php'); ?>